package api

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"time"
)

var (
	datetime string
	welcome  string
)

const (
	author string = "venki.chen"
)

func init() {
	now := time.Now()
	datetime = now.Format("2006-01-02 15:04:05")
	welcome = author + "欢迎你来到今日的golang语言学习，现在的时间是：" + datetime
}

func Access() {
	fmt.Println(welcome)
	fmt.Println("-----------------")
	// 移动文件
	// FileMove()
	// 判断文件或者文件夹是否存在
	// fmt.Println(PathExists("../other/venki.txt"))
	// 拷贝文件
	/*_, err := CopyFile("../another/01_bak.jpg", "../other/01.jpg")
	if err != nil {
		fmt.Printf("when pc are coping err=%v\n", err)
	}
	fmt.Println("copy文件成功……")*/
	// CalcTypeStringNumber("../other/poet.txt")
	// 获取命令行参数
	fmt.Println("命令行里面的参数：", len(os.Args))
	for i, v := range os.Args {
		fmt.Printf("args[%v]=%v\n", i, v)
	}
}

type CharCount struct {
	ChCount    int // 记录英文个数
	NumCount   int // 记录数字个数
	SpaceCount int // 记录空格个数
	OtherCount int // 记录其他个数
}

// CalcTypeStringNumber 统计文件中不同字符的数量
func CalcTypeStringNumber(filePath string) {
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Printf("when pc are reading file err=%v\n", err)
		return
	}
	defer file.Close()
	var count CharCount
	reader := bufio.NewReader(file)
	for {
		str, err := reader.ReadString('\n')
		if err == io.EOF { // 督导读到文件末尾结束循环
			break
		}
		// 遍历str，进行统计
		for _, v := range str {
			// fmt.Printf("统计每一行的字符数量：%v\n", v)
			switch {
			case v >= 'a' && v <= 'z':
				fallthrough
			case v >= 'A' && v <= 'Z':
				count.ChCount++
			case v == ' ' || v == '\t':
				count.SpaceCount++
			case v >= '0' && v <= '9':
				count.NumCount++
			default:
				count.OtherCount++
			}
		}
	}
	fmt.Printf("字符的个数为：%v,数字个数为：%v,空格字符为：%v,其他字符个数为：%v",
		count.ChCount, count.NumCount, count.SpaceCount, count.OtherCount)
}

// CopyFile 文件拷贝
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {
	srcfile, err := os.Open(srcFileName)
	if err != nil {
		fmt.Printf("when pc are opening srcfile err=%v\n", err)
	}
	defer srcfile.Close()
	reader := bufio.NewReader(srcfile)

	dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Printf("when pc are opening dstFile err=%v\n", err)
		return
	}
	defer dstFile.Close()
	writer := bufio.NewWriter(dstFile)
	return io.Copy(writer, reader)
}

// PathExists 判断文件或者目录是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil // 文件或者文件夹存在
	}
	if os.IsNotExist(err) {
		return false, nil // 文件或者文件夹不存在
	}
	return false, nil
}

// FileMove 文件迁移
func FileMove() {
	file1Path := "../other/venki.txt"
	file2Path := "../another/chen.txt"
	data, err := ioutil.ReadFile(file1Path)
	if err != nil {
		fmt.Printf("when pc are reading file1 ,err=%v\n", err)
	}

	err = ioutil.WriteFile(file2Path, data, 0666)

	if err != nil {
		fmt.Printf("when pc are writing file2 ,err=%v\n", err)
	}
}
